package com.metagurukul.metagranth.actionservlets;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.metagurukul.metagranth.service.QuestionService;
import com.metagurukul.metagranth.vo.MetaData;

/**
 * Servlet implementation class GetLatestQuestionServlet
 * This servlet is responsible for getting the list of latest fifteen questions posted so far on the site
 * along with the metaData associated with those questions which are displayed on the home page of user
 * 
 * @author team MetaGranth
 *
 */
public class GetLatestQuestionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetLatestQuestionServlet() {
		super();
	
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPerform(request, response);
	}

	/**
	 * this function will call getLatestQuestions function in the QuestionService layer that will bring the metadata
	 * of latest 15 Questions asked so far
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doPerform(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		if(session.getAttribute("userId")!=null){
		try{
		//gets Latest 15 Questions asked on the site so far by calling getLatestQuestions function 
		ArrayList<MetaData> metaDataList=QuestionService.getLatestQuestions();
		request.setAttribute("metaDataList", metaDataList);
		request.getRequestDispatcher("home.jsp").forward(request, response);
	}catch(Exception exception) {
		request.setAttribute("errormsg", exception.getMessage());
		request.getRequestDispatcher("errorPage.jsp").forward(request, response);
	}
		}else {
			response.sendRedirect("index.jsp");
		}
	}
}
